package com.qsmx.qingqiuticket.app.delegate;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.banner.HolderCreator;
import com.qsmx.qingqiuticket.app.databinding.DelegateHomeBinding;
import com.qsmx.qingqiuticket.app.delegate.back.PasswordDelegate;
import com.qsmx.qingqiuticket.app.delegate.group.GroupBuyDelegate;
import com.qsmx.qingqiuticket.app.delegate.mem.MemHomeDelegate;
import com.qsmx.qingqiuticket.app.event.HomeRefreshBannerEvent;
import com.qsmx.qingqiuticket.app.event.HomeRefreshEvent;
import com.qsmx.qingqiuticket.app.event.HomeShowVideoEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.util.CameraManager;
import com.qsmx.qingqiuticket.app.util.DownloadUtil;
import com.qsmx.qingqiuticket.app.util.FileUtil;
import com.qsmx.qingqiuticket.app.util.SaveHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;

public class HomeDelegate extends AtmosDelegate {
    private int clickNum = 0;
    private String mTopVideoUrl = "https://media.w3.org/2010/05/sintel/trailer.mp4";
    private String mBottomVideoUrl = "https://media.w3.org/2010/05/sintel/trailer.mp4";

    private DelegateHomeBinding mBinding;

    @Override
    public Object setLayout() {
        return R.layout.delegate_home;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        mBinding = DelegateHomeBinding.bind(rootView);
        onClick();
        FileUtil.deleteFolderFile(SaveHelper.getBasePath());
        try {
            if (FusionData.mAdvData.getBody().getSaleTicketFirstType().equals("2")) {
                initTopVideo();
                mTopVideoUrl = FusionData.mAdvData.getBody().getSaleTicketFirstVideoUrl();
            }
            if (FusionData.mAdvData.getBody().getSaleTicketSecondType().equals("2")) {
                initBottomVideo();
                mBottomVideoUrl = FusionData.mAdvData.getBody().getSaleTicketSecondVideoUrl();
            }
        } catch (Exception e) {

        }
        initBannerInfo();
    }

    private void initTopVideo() {

        JZDataSource jzDataSource = new JZDataSource(FusionCode.DOWNLOAD_SAVE_VIDEO_PATH + "ticket_top.mp4");
        jzDataSource.looping = true;
        mBinding.topVideo.setUp(jzDataSource, Jzvd.SCREEN_NORMAL);
        mBinding.topVideo.startVideoAfterPreloading();
        mBinding.topVideo.setClickable(false);
    }

    private void initBottomVideo() {

        JZDataSource jzDataSource = new JZDataSource(FusionCode.DOWNLOAD_SAVE_VIDEO_PATH + "ticket_bottom.mp4");
        jzDataSource.looping = true;
        mBinding.bottomVideo.setUp(jzDataSource, Jzvd.SCREEN_NORMAL);
        mBinding.bottomVideo.startVideoAfterPreloading();
        mBinding.bottomVideo.setClickable(false);

    }

    private void initBannerInfo() {
        if (StringUtil.isNotEmpty(FusionData.mAdvData.getBody().getSaleTicketFirstType()) && (StringUtil.isNotEmpty(FusionData.mAdvData.getBody().getSaleTicketFirstVideoUrl()) || FusionData.mAdvData.getBody().getFirstAttachmentUrl() != null)) {
            if (FusionData.mAdvData.getBody().getSaleTicketFirstType().equals("1")) {
                mBinding.cbTopBanner.setVisibility(View.VISIBLE);
                mBinding.cbTopBanner.setPages(new HolderCreator(), FusionData.mAdvData.getBody().getFirstAttachmentUrl())
                        .setPageIndicator(new int[]{R.drawable.dot_normal, R.drawable.dot_selected})
                        .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                        .startTurning(3000)
                        .setCanLoop(true);
            } else {
                mBinding.cbTopBanner.setVisibility(View.GONE);
                DownloadUtil.DownLoadVideoFile(getContext(), mTopVideoUrl, "");
                mBinding.topVideo.setVisibility(View.VISIBLE);
            }
        }

        if (StringUtil.isNotEmpty(FusionData.mAdvData.getBody().getSaleTicketSecondType()) && (StringUtil.isNotEmpty(FusionData.mAdvData.getBody().getSaleTicketSecondVideoUrl()) || FusionData.mAdvData.getBody().getSecondAttachmentUrl() != null)) {

            if (FusionData.mAdvData.getBody().getSaleTicketSecondType().equals("1")) {
                mBinding.cbBottomBanner.setVisibility(View.VISIBLE);
                mBinding.cbBottomBanner.setPages(new HolderCreator(), FusionData.mAdvData.getBody().getSecondAttachmentUrl())
                        .setPageIndicator(new int[]{R.drawable.dot_normal, R.drawable.dot_selected})
                        .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                        .startTurning(3000)
                        .setCanLoop(true);
            } else {
                mBinding.cbBottomBanner.setVisibility(View.GONE);
                DownloadUtil.DownLoadBottomVideoFile(getContext(), mBottomVideoUrl, "");
                mBinding.bottomVideo.setVisibility(View.VISIBLE);
            }
        }
    }

    private void onClick() {
        mBinding.tvGoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (clickNum < 4) {
                    clickNum += 1;
                } else {
                    getSupportDelegate().start(new PasswordDelegate());
                    clickNum = 0;
                }
            }
        });

        mBinding.ivBuyTicketNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkMachineTicketSet()) {
                    getSupportDelegate().start(new PackageListDelegate());
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "未设置机台票数量，请联系门店管理员！", "确定");
                }
            }
        });

        mBinding.ivGetTicket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkMachineTicketSet()) {
                    getSupportDelegate().start(new MemHomeDelegate());
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "未设置机台票数量，请联系门店管理员！", "确定");
                }
            }
        });

        mBinding.ivGroupUse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkMachineTicketSet()) {
                    getSupportDelegate().start(new GroupBuyDelegate());
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "未设置机台票数量，请联系门店管理员！", "确定");
                }
            }
        });
    }

    private boolean checkMachineTicketSet() {
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM))) {
            return false;
        }
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM))) {
            return false;
        }
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM))) {
            return false;
        }
        return true;
    }

    private void cleanSessionInfo() {

        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));

        HttpHelper.RestClientPostRaw(params, HttpUrl.CLEAR_SESSION,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {

                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        cleanSessionInfo();
        FusionData.mMemData = null;
        if (FusionData.mAdvData.getBody().getSaleTicketFirstType().equals("2")) {
            mBinding.topVideo.startVideoAfterPreloading();
        }
        if (FusionData.mAdvData.getBody().getSaleTicketSecondType().equals("2")) {
            mBinding.bottomVideo.startVideoAfterPreloading();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefresh(HomeRefreshEvent event) {
        if (event != null && event.getData() != null) {
            if (FusionData.mAdvData != null) {
                mTopVideoUrl = FusionData.mAdvData.getBody().getSaleTicketFirstVideoUrl();
                mBottomVideoUrl = FusionData.mAdvData.getBody().getSaleTicketSecondVideoUrl();
                initBannerInfo();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowVideo(HomeShowVideoEvent event) {
        if (event != null && event.getData() != null) {
            if (FusionData.mAdvData.getBody().getSaleTicketFirstType().equals("2")) {
                initTopVideo();
            }
            if (FusionData.mAdvData.getBody().getSaleTicketSecondType().equals("2")) {
                initBottomVideo();
            }
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (FusionData.mAdvData.getBody().getSaleTicketFirstType().equals("2")) {
            Jzvd.releaseAllVideos();
        }
        if (FusionData.mAdvData.getBody().getSaleTicketSecondType().equals("2")) {
            Jzvd.releaseAllVideos();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
